/***************************************************
> Copyright (C) 2024 ==QWZL== All rights reserved.
> File Name: register.c
> Author:nxq
> Mail:nxq949698473@163.com 
> Created Time: 2024年07月24日 星期三 16时51分38秒
***************************************************/

#include "WPH_server.h"
#include "register.h"
#include "sql.h"


//管理员登录
void managerLog(int sock,char*buf)
{
    int ret = 0;
    int value = 0;

    struct log info = manager(buf);//注册管理员信息解包

    struct reg *head ;
    head = (struct reg *)malloc(sizeof(struct reg));
    memset(head,0,sizeof(struct reg));

    head = readMysqlInfo();//读取管理员表中信息
    struct reg *reg = head->next;

    LOG_D("info.account = %d ,info.cipher = %d",info.account,info.cipher);

    while(reg != NULL)
    {     
        LOG_D("reg->account = %d ,reg->cipher = %d\n",reg->account,reg->cipher);

        if((info.account == reg->account) && (info.cipher == reg->cipher))
        {
            LOG_D("value1 = %d\n",value);
            value = 1;//成功
            break;
        }
        else
        {       
            LOG_D("value2 = %d\n",value);    
            value = 0;//失败         
        }   
        reg  = reg ->next;
    }

    ret = send(sock,&value,4,0);
    if(ret == -1)
    {
        LOG_E("sendto\n"); 
        exit(-1);
    }
    close(sock);

    struct reg*temp = NULL;
    //释放 
    while(head != NULL)
    {
        temp = head;
        free(temp);
        temp = NULL;
        head = head->next;
    }
}

//管理员登录解包
//注册管理员信息解包
struct log manager(char *buf)
{
    struct log info;
    memset(&info,0,sizeof(info));
    char type[30] = {0};

    //定义cJSON指针
    cJSON *json = NULL;
    //将字符串转为json格式对象
    json = cJSON_Parse(buf);

    cJSON *node = NULL;
    //由键获取值
    node = cJSON_GetObjectItem(json,"type");
    if(node == NULL)
    {
        //printf("can't find type\n");
        LOG_E("can't find type"); 
        exit(-1);
    }
    if(node->type == cJSON_String)
    {
        strcpy(type,node->valuestring);
    }

    node = cJSON_GetObjectItem(json,"account");
    if(node == NULL)
    {
        LOG_E("can't find account"); 
        exit(-1);
    }
    if(node->type == cJSON_Number)
    {
        info.account = node->valueint;
    }

    node = cJSON_GetObjectItem(json,"cipher");
    if(node == NULL)
    {
        LOG_E("can't find cipher"); 
        exit(-1);
    }
    if(node->type == cJSON_Number)
    {
        info.cipher = node->valueint;
    }
   
    cJSON_Delete(json);	
    return info;
}